<template>
  <a-upload
    :max-count="1"
    :action="action"
    :multiple="true"
    :file-list="fileList"
    :headers="headers"
    accept=".xlsx,.xls"
    @change="handleChange"
    :before-upload="beforeUpload"
  >
    <a-button>
      <upload-outlined></upload-outlined>
      Upload
    </a-button>
  </a-upload>
</template>
<script>
import { UploadOutlined } from '@ant-design/icons-vue'
import { defineComponent, ref } from 'vue'
import { message } from 'ant-design-vue'

export default defineComponent({
  components: {
    UploadOutlined
  },
  setup(props, context) {
    //接收父组件传递过来的数据
    let action = ref(props.action)
    //触发父组件方法
    var plusOne = () => {
      context.emit('upload', '我是子组件传递到父组件的数据')
    }

    const fileList = ref([])
    const beforeUpload = (file) => {
      return new Promise((resolve) => {
        if (
          file.type !== 'application/vnd.ms-excel' &&
          file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ) {
          message.error('只能上传excel文件')
          return false
        }
        //&& file.type !== 'text/csv'
        resolve(file)
      })
    }
    const handleChange = (info) => {
      let resFileList = [...info.fileList]

      resFileList = resFileList.slice(-2)

      resFileList = resFileList.map((file) => {
        if (file.response) {
          file.url = file.response.url
        }
        return file
      })
      fileList.value = resFileList
      //当文件上传成功后，触发父组件的方法
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功.`)
        let file = fileList.value[0].response.data
        context.emit('upload', file)
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败.`)
      }
    }
    //获取本地存储的token
    let token = localStorage.getItem('token')
    const headers = {
      Authorization: token
    }
    return {
      fileList,
      action,
      handleChange,
      headers,
      beforeUpload
    }
  }
})
</script>
